package com.atguigu.tingshu.account.consumer;

import com.atguigu.tingshu.account.mapper.UserAccountMapper;
import com.atguigu.tingshu.model.account.UserAccount;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.log4j.Log4j2;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/***
 * 初始化账户消费者
 */
@Component
@Log4j2
public class UserAccountInitConsumer {
    @Autowired
    private UserAccountMapper userAccountMapper;

    @RabbitListener(queues = "UserAccountQueue")
    @SneakyThrows
    public void userAccountConsumer(Channel channel, Message message ) {
        //接收消息
        String userid = new String(message.getBody());
        //获取消息属性
        MessageProperties messageProperties = message.getMessageProperties();
        //获取消息编号
        long deliveryTag = messageProperties.getDeliveryTag();

        try {
            //初始化账号
            UserAccount userAccount = new UserAccount();
            userAccount.setUserId(Long.valueOf(userid));
            userAccountMapper.insert(userAccount);
            //手动消息确认
            channel.basicAck(deliveryTag,false);
        }catch (Exception e){
            //日志记录消息发送失败原因
            log.error("初始化账户失败，用户id："+userid+"失败原因是："+e.getMessage());
            //判断否是发过一次消息
            if (messageProperties.getRedelivered()){
                channel.basicReject(deliveryTag,false);
            }else {
                //是第一次发，放回队列再发一次
                channel.basicReject(deliveryTag,true);
            }
        }
    }
}
